# coding:utf-8
# 曾山
# 时间 2022/5/4 14:15
from itsdangerous import TimedJSONWebSignatureSerializer
from comment.utils.const import SECRET_KEY,JWT_EXPIPY_SECOND
from flask import current_app
from comment.models.user import User
def generate_tokens(uid):
    '''
    根据已经登录之后的用户id，生成token
    :param uid:
    :return:
    '''
    #参数一：密钥
    #参数二：token过期时间
    s = TimedJSONWebSignatureSerializer(secret_key=SECRET_KEY,expires_in=JWT_EXPIPY_SECOND)
    # 生成token
    return s.dumps({'id':uid}).decode()



def verify_tokens(token_str):
    '''
    验证token 验证成功之后 返回用户id
    :param token_str:
    :return:
    '''
    s = TimedJSONWebSignatureSerializer(secret_key=SECRET_KEY)
    try:
        data = s.loads(token_str)
    except Exception as e:
        current_app.logger.info(e)
        return {'message':'token'}

    #如果token验证成功，还需要看看当前用户状态是否正常
    user = User.query.filter(User.id==data['id']).first()
    if user and user.status != 0:
        return {'message':'数据库中的用户状态过期'}
    return {'id':user.id}
